import os
from django.shortcuts import render,redirect
from django.http import HttpResponse
import uuid
import random
from user_app import models, user_tool
from django.views.decorators.csrf import csrf_exempt
import json
import os,sys
from cin_tic_sal import models as cin_models
from cinema_app import models as cinema_models
from movie_app import models as movie_models
# Create your views here.


@csrf_exempt
#用户登录
def Login(request):       #基于session的用户登录
    if request.method == 'POST':
        user = request.POST.getlist('username')
        try:                                      #验证用户是否存在
            user_msg = models.User_info.objects.get(account = user[0])
        except:
            msg= {'Login_msg':'用户不存在'}
            res = HttpResponse(json.dumps(msg),content_type="application/json")
            return res
        if(user_msg.get_state_display() == '封禁'):
            msg={'Login_msg':'用户已被封禁'}
            res = HttpResponse(json.dumps(msg),content_type="application/json")
            return res
        pasw = request.POST.getlist('password')
        if(user_msg.password == pasw[0]):
            msg= {'Login_msg':'登录成功'}
        else:
            msg= {'Login_msg':'密码错误'}
            res = HttpResponse(json.dumps(msg),content_type="application/json")
            return res
        #验证通过
        request.session['is_login'] = True
        request.session['username'] = user_msg.username
        request.session['user_id'] = user_msg.id
        request.session['type'] = 3
        res = HttpResponse(json.dumps(msg),content_type="application/json")
        res.set_cookie('is_login',True,max_age=7*12*3600)
        res.set_cookie('username',json.dumps(user_msg.username),max_age=7*12*3600)
        res.set_cookie('userimag',user_msg.H_photo,max_age=7*12*3600)
        res.set_cookie('account',user_msg.account,max_age=7*12*3600)
        return res
        #return render(request, 'Test_index.html', msg)
    else:
        return redirect("/news")

@csrf_exempt
#用户注册
def register(request):
    if request.method == "POST":
        account =  request.POST.getlist('account')[0]
        password = request.POST.getlist('Password1')[0]
        user_tool.getuserid()
        #判断账号密码是否符合格式
        valid = user_tool.validation_pa(account,password)
        #如果账号密码不符合要求
        if not valid['result']:
            msg = {'msg': valid['msg']}
            res = HttpResponse(json.dumps(msg),content_type="application/json")
            return res
        #判断账号名是否已经占用
        users = models.User_info.objects.filter(account = account)
        if users.exists() :
            #用户已经存在
            msg = {'msg': "账号已经存在"}
            res = HttpResponse(json.dumps(msg),content_type="application/json")
            return res
        #向数据库存入数据
        try:
            user = models.User_info(account = account)
            #生成用户id
            user.id = user_tool.getuserid()
            user.username = "新用户"
            user.password = password
            user.save()
        except:
            msg = {'msg': "服务器错误"}
            res = HttpResponse(json.dumps(msg),content_type="application/json")
            return res
        msg = {'msg': "注册成功"}
        res = HttpResponse(json.dumps(msg),content_type="application/json")
        return res
    else:
        return render(request, 'register.html')

#用户注销
def Loginout(request):
    request.session.flush() #删除session
    res = redirect('../')
    res.delete_cookie('username')
    res.delete_cookie('is_login')
    res.delete_cookie('sessionid')
    return res

#用户主页
#用户个人中（资料修改）
@csrf_exempt
def home(request):
    if(request.method == "POST"):
        #个人中心资料修改
        user = models.User_info.objects.get(id = request.session['user_id'])
        try:
            userimg = request.FILES.get('userimg')
            if userimg.size >= 3145728:
                msg = {'msg':"文件大于3M"}
                res = HttpResponse(json.dumps(msg),content_type="application/json")
                return res
            somue,imgpat = userimg.name.split(".",1)
            imgname = user_tool.getimgid() +"."+imgpat
            img_path = os.path.join('./static/user_imag/', imgname)
            with open(img_path, 'wb') as fi:
                for i in userimg.chunks():
                    fi.write(i)
            oldimg = user.H_photo
            user.H_photo = "/"+img_path[2:]
        except:
            #未上传图片
            pass
        oldimgdir = sys.argv[0][:-10]  + oldimg
        os.remove(oldimgdir)
        username = request.POST.getlist('username')[0]
        usertel = request.POST.getlist('usertel')[0]
        usermail = request.POST.getlist('usermail')[0]
        userwechat = request.POST.getlist('userwechat')[0]
        try:
            user.username = username
            user.email = usermail
            user.wechat = userwechat
            user.phone_num = usertel
        except:
            msg = {'msg':"数据错误"}
            res = HttpResponse(json.dumps(msg),content_type="application/json")
            return res
        user.save()
        msg = {'msg':"保存成功"}
        res = HttpResponse(json.dumps(msg),content_type="application/json")
        res.set_cookie('userimag',user.H_photo,max_age=7*12*3600)
        return res

    else:
        user = models.User_info.objects.get(id = request.session['user_id'])
        img = user.H_photo
        username = user.username
        telnumber = user.phone_num
        email = user.email
        wechat = user.wechat
        content = {'userimg':img,'username':username,
                   'telnumber':telnumber,'email':email,'wechat':wechat}
        return render(request,'home.html',content)

#用户密码修改
@csrf_exempt
def repassword(request):
    if request.method == "POST":
        oldpassword = request.POST.getlist('re_oldpassword')[0]
        pass1 = request.POST.getlist('re_newpassword')[0]
        pass2 = request.POST.getlist('re_secpassword')[0]
        user = models.User_info.objects.get(id = request.session['user_id'])
        #判断旧密码是否正确
        if oldpassword != user.password:
            msg = {'msg':"旧密码错误"}
            res = HttpResponse(json.dumps(msg),content_type="application/json")
        #判断密码是否符合标准
        elif len(pass1)<6:
            msg = {'msg':"密码必须大于6位"}
            res = HttpResponse(json.dumps(msg),content_type="application/json")
        else:
            user.password = pass1
            user.save()
            msg = {'msg':"修改成功"}
            res = HttpResponse(json.dumps(msg),content_type="application/json")
        return res

#用户订单页面
def sessionpage(request):
    bccolorlist = ['#ECA3F5','#98DDCA','#FFC2B4','#99F3BD']
    user = models.User_info.objects.get(id = request.session["user_id"])
    order_list = cin_models.Order_info.objects.filter(user_account=user.account)
    foo = len(order_list)
    content= {"foo":foo}
    content['orderlist'] = ""
    if foo > 0:
        for order in order_list:
            session = cinema_models.Session_info.objects.get(id = order.session_id)
            cinema = cinema_models.cinema.objects.get(id=session.cinema_id)
            movie = movie_models.Movie_info.objects.get(id = session.movie_id)
            i = random.randint(0,len(bccolorlist)-1)
            data1 = movie.name +"-"+cinema.addr
            data2 = str(session.be_time)
            data3 = cinema.addr
            data4 = session.Location +" "+order.seat
            line = '<div class="card" style="width: 100%;margin-top: 10px;background-color:'+bccolorlist[i]+';cursor: default;"><div class="card-body"><h5 class="card-title">'+data1+'</h5><h6 class="card-subtitle mb-2 text-muted"><b>时间：</b>'+data2+'</h6><a class="card-text"><b>影院位置：</b>'+data3+'</a><p class="card-text"><b>具体位置：</b>'+data4+'</p></div></div>'
            content["orderlist"] = content["orderlist"]+line
            return render(request,"sessionpage.html",content)
    else:
        return render(request,"sessionpage.html",content)